import { defineStore } from 'pinia'
import { wxLogin as wxLoginApi, updateProfile as updateProfileApi } from '@/api/user'
import { getDeliveryEntryStatus } from '@/api/deliveryEntry'
import config from '@/config'

export const useUserStore = defineStore('user', {
  state: () => ({
    isLogin: false,
    userInfo: null,
    accessToken: '',
    refreshToken: '',
    deliveryId: ''
  }),
  getters: {
    nickname: (state) => state.userInfo?.nickname || '配送员',
    avatar: (state) => state.userInfo?.avatar || '/static/images/default-avatar.png',
    loggedIn: (state) => state.isLogin && state.accessToken
  },
  actions: {
    /**
     * 静默登录，获取配送员用户信息
     * @returns {Promise<Object>} 配送员用户信息
     */
    login() {
      return new Promise((resolve, reject) => {
        uni.login({
          provider: 'weixin',
          success: (loginRes) => {
            this.wxLogin(loginRes.code)
              .then(resolve)
              .catch(reject)
          },
          fail: reject
        })
      })
    },
    /**
     * 微信登录
     * @param {string} code
     * @returns {Promise<Object>}
     */
    async wxLogin(code) {
      try {
        const { data } = await wxLoginApi(code)
        this.isLogin = true
        this.userInfo = data.userInfo
        this.accessToken = data.accessToken
        this.refreshToken = data.refreshToken
        this.deliveryId = data.deliveryId
        uni.setStorageSync('accessToken', this.accessToken)
        uni.setStorageSync('refreshToken', this.refreshToken)
        uni.setStorageSync('deliveryId', this.deliveryId)
        uni.setStorageSync('userInfo', JSON.stringify(this.userInfo))
        
        // 检查是否需要获取顾客端openid
        if (data.needCustomerOpenid) {
          await this.jumpToCustomerMiniProgram(data.deliveryOpenid)
          return data
        }
        
        // 登录成功后检查配送员入驻状态
        await this.checkDeliveryEntryStatus()
        return data
      } catch (error) {
        console.error('微信登录失败:', error)
        throw error
      }
    },
    /**
     * 检查配送员入驻状态并跳转
     */
    async checkDeliveryEntryStatus() {
      if (!this.userInfo?.id) return
      try {
        const { data } = await getDeliveryEntryStatus(this.userInfo.id)
        switch (data.status) {
          case '未入驻':
            uni.redirectTo({ url: '/pages/entry/apply' })
            break
          case '审核中':
            uni.redirectTo({ url: '/pages/entry/pending' })
            break
          case '审核拒绝':
            uni.redirectTo({ url: `/pages/entry/reject?reason=${encodeURIComponent(data.rejectReason || '')}` })
            break
          case '审核通过':
            uni.switchTab({ url: '/pages/index/index' })
            break
        }
      } catch (e) {
        console.error('入驻状态查询失败', e)
      }
    },

    /**
     * 退出登录
     */
    logout() {
      this.isLogin = false
      this.userInfo = null
      this.accessToken = ''
      this.refreshToken = ''
      this.deliveryId = ''
      uni.removeStorageSync('accessToken')
      uni.removeStorageSync('refreshToken')
      uni.removeStorageSync('userInfo')
      uni.removeStorageSync('deliveryId')
    },
    /**
     * 初始化用户状态，从本地存储恢复
     */
    initUserState() {
      const accessToken = uni.getStorageSync('accessToken')
      const refreshToken = uni.getStorageSync('refreshToken')
      const userInfoStr = uni.getStorageSync('userInfo')
      const deliveryId = uni.getStorageSync('deliveryId')
      if (accessToken && refreshToken && userInfoStr && deliveryId) {
        try {
          this.accessToken = accessToken
          this.refreshToken = refreshToken
          this.userInfo = JSON.parse(userInfoStr)
          this.deliveryId = deliveryId
          this.isLogin = true
          
        } catch (e) {
          console.error('Failed to parse user info:', e)
          this.logout()
        }
      } else {
        // 自动静默登录
        this.login().catch(err => {
          console.error('自动登录失败:', err)
        })
      }
    },
    /**
     * 刷新token后更新本地token
     */
    updateToken({ accessToken, refreshToken }) {
      this.accessToken = accessToken
      this.refreshToken = refreshToken
      uni.setStorageSync('accessToken', accessToken)
      uni.setStorageSync('refreshToken', refreshToken)
    },
    /**
     * 跳转到顾客端小程序获取openid
     * @param {string} deliveryOpenid 配送员openid
     */
    async jumpToCustomerMiniProgram(deliveryOpenid) {
      return new Promise((resolve, reject) => {
        uni.showModal({
          title: '需要获取授权',
          content: '为了支持微信支付分账功能，需要跳转到顾客端小程序进行一次授权，该操作只需要进行一次。',
          confirmText: '立即授权',
          cancelText: '稍后再说',
          success: (res) => {
            if (res.confirm) {
               // 跳转到顾客端小程序
               uni.navigateToMiniProgram({
                 appId: config.customerAppId, // 顾客端小程序appid
                 path: `/pages/auth/openid?deliveryOpenid=${deliveryOpenid}`,
                 envVersion: config.envVersion, // 根据环境自动选择版本
                 success: () => {
                   console.log('跳转顾客端小程序成功')
                   resolve()
                 },
                 fail: (err) => {
                   console.error('跳转顾客端小程序失败:', err)
                   uni.showToast({
                     title: '跳转失败，请稍后重试',
                     icon: 'none'
                   })
                   reject(err)
                 }
               })
            } else {
              // 用户取消，继续正常流程
              resolve()
            }
          }
        })
      })
    },
    
    /**
     * 更新用户信息（昵称和头像）
     * @param {Object} payload { id, nickname, avatar }
     * @returns {Promise<Object>} 更新后的用户信息
     */
    async updateProfile({ id, nickname, avatar }) {
      try {
        const { data } = await updateProfileApi({ id, nickname, avatar })
        this.userInfo = data
        uni.setStorageSync('userInfo', JSON.stringify(this.userInfo))
        return data
      } catch (error) {
        console.error('更新用户信息失败:', error)
        throw error
      }
    },
  }
})